package com.example.ai

import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.ViewModelProvider
import com.example.ai.model.data.ChatRoomData
import com.example.ai.model.data.MessageDatabase
import com.example.ai.model.viewmodel.MessageViewModel
import com.example.ai.model.viewmodel.ViewModelFactory
import com.example.ai.page.TextChatPage
import com.example.ai.ui.theme.AITheme

class MainActivity : ComponentActivity() {
    companion object {
        const val DEFAULT_TITLE = "莉莉"
        const val DEFAULT_ID = "1314520"
        const val ARG_TITLE = "title"
        const val ARG_ID = "id"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val database = MessageDatabase.getInstance(this@MainActivity)
        val title = intent.getStringExtra(ARG_TITLE) ?: DEFAULT_TITLE
        val id = intent.getStringExtra(ARG_ID) ?: DEFAULT_ID
        val viewModel = ViewModelProvider(this@MainActivity, ViewModelFactory {
            MessageViewModel(chatRoom = ChatRoomData(id, title), database)
        })[MessageViewModel::class.java].apply {
            prepare()
        }
        setContent {
            AITheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier
                        .fillMaxSize()
                        .windowInsetsPadding(WindowInsets.statusBars)
                        .windowInsetsPadding(WindowInsets.navigationBars),
                    color = MaterialTheme.colorScheme.background
                ) {
                    if (viewModel.netWorkError.value) {
                        Toast.makeText(this, "网络错误，当前无法聊天.", Toast.LENGTH_SHORT).show()
                        viewModel.resetNetworkError()
                    }
                    TextChatPage(viewModel = viewModel,)
                }
            }
        }
    }
}
